package com.cdhkppm.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cdhkppm.constant.HKErrorCodeEnum;
import com.cdhkppm.constant.TestErrorCodeEnum;
import com.cdhkppm.dto.CustomExcelImportActiveStrDTO;
import com.cdhkppm.utils.FastJsonUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hustcad.plm.rpm.model.dto.active.PlusTaskSaveDTO;
import com.hustcad.plm.rpm.service.plan.TyppmGanttChartService;
import com.hustcad.plm.rpm.serviceextend.impl.ImportDataExtendServiceImpl;
import com.hustcad.plm.rpm.util.excel.util.ExcelUtils;
import com.ty.basic.constant.TableTypeConstrant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yfq
 * @apiNote
 */

@Slf4j
@Service
@Primary
public class CustomImportDataExtendServiceImpl extends ImportDataExtendServiceImpl{

    @Resource
    private TyppmGanttChartService ganttChartService;


    public JSONArray importPlanActiveByExcelAfter(JSONArray array, MultipartFile file, String planOid,
                                                  Map<String, String> fieldMap) {
        try {
            if (CollectionUtils.isEmpty(array)) {
                log.info("任务树为空，直接返回");
                return array;
            }

            List<CustomExcelImportActiveStrDTO> excelList = ExcelUtils.excelToList(file, 2,
                                                                                   CustomExcelImportActiveStrDTO.class,
                                                                                   fieldMap);
            List<CustomExcelImportActiveStrDTO> filteredList = new ArrayList<>(excelList);
            if (CollectionUtils.isEmpty(filteredList)) {
                log.info("Excel 数据为空");
                return array;
            }
            List<PlusTaskSaveDTO> plusTaskSaveDTOList = new ArrayList<>();
            for (int i = 0; i < array.size(); i++) {
                JSONObject obj = array.getJSONObject(i);
                buildTaskDtoRecursive(obj, planOid, plusTaskSaveDTOList);
            }

            Map<String, PlusTaskSaveDTO> plusTaskMap = plusTaskSaveDTOList.stream()
                    .collect(Collectors.toMap(PlusTaskSaveDTO::getName, dto -> dto));

            for (CustomExcelImportActiveStrDTO customDTO : filteredList) {
                String activeName = customDTO.getActiveName();
                PlusTaskSaveDTO target = plusTaskMap.get(activeName);
                if (target != null) {
                    // 添加扩展属性
                    Map<String, List<String>> ibaAttribute = buildIbaAttribute(customDTO);
                    target.setIbaAttribute(ibaAttribute);
                }
            }
            ganttChartService.saveTableTreeEx(planOid, plusTaskSaveDTOList);

            return array;

        } catch (Exception e) {
            log.error("导入计划任务扩展属性失败", e);
            throw HKErrorCodeEnum.EXPORT_TYPE_NOT_EXIST.getException("导入计划任务扩展属性失败: " + e.getMessage(), e);
        }
    }



    /**
     * 递归构建任务节点并添加进列表
     */
    private void buildTaskDtoRecursive(JSONObject obj, String planOid, List<PlusTaskSaveDTO> list) {
        PlusTaskSaveDTO dto = new PlusTaskSaveDTO();

        String finishDateStr = FastJsonUtil.getJsonString(obj,"Finish","finish");
        String startDateStr = FastJsonUtil.getJsonString(obj,"start","Start");
        String earlyFinishDateStr = FastJsonUtil.getJsonString(obj,"earlyFinish","EarlyFinish");
        String earlyStartDateStr = FastJsonUtil.getJsonString(obj,"earlyStart","EarlyStart");
        String lateFinishDateStr = FastJsonUtil.getJsonString(obj,"lateFinish","LateFinish");
        String lateStartDateStr = FastJsonUtil.getJsonString(obj,"lateStart","LateStart");

        dto.setConstraintDate(formatDateTimeStrWithSeconds(finishDateStr));
        dto.setStartDate(formatDateTimeStrWithSeconds(startDateStr));
        dto.setConstraintType("0");
        dto.setDuration(obj.getString("Duration"));
        dto.setFinishDate(formatDateTimeStrWithSeconds(earlyFinishDateStr));
        dto.setEarlyStart(formatDateTimeStrWithSeconds(earlyStartDateStr));
        dto.setLateFinish(formatDateTimeStrWithSeconds(lateFinishDateStr));
        dto.setLateStart(formatDateTimeStrWithSeconds(lateStartDateStr));

        dto.setEffortDriven(obj.getString("EffortDriven"));
        dto.setMilestone(obj.getString("Milestone"));
        dto.setName(obj.getString("Name"));
        dto.setOutLineLevel(obj.getString("OutlineLevel"));
        dto.setParentOID(planOid);
        dto.setParentOTYPE(TableTypeConstrant.TY_PLAN_OTYPE);
        dto.setPercentWorkComplete("0");
        dto.setSummary(obj.getString("Summary"));
        dto.setMarkForDelete("0");
        dto.setWork(obj.getString("Work"));
        dto.setAfterDeadline(obj.getString("AfterDeadline"));
        dto.setBeforeDeadline(obj.getString("BeforeDeadline"));
        dto.setContainerOID(obj.getString("containerOID"));
//        dto.setConstraintType(TableTypeConstrant.TY_PROJECT_TYPE);
        dto.setControlled(obj.getString("controlled"));
        dto.setEffortDriven(obj.getString("effortDriven"));
        dto.setHealthStatusType("UNAVAILABLE");
        dto.setLineNumber(obj.getString("ID"));
        dto.setIsTemplate(obj.getString("isTemplate"));
        dto.setJobOID(obj.getString("jobOID"));
        dto.setLockStatus(obj.getString("lockStatus"));
        dto.setLockUserOid(obj.getString("lockUserOid"));
        dto.setOid(obj.getString("id"));
        dto.setOtype(TableTypeConstrant.TY_PLAN_ACTIVITY_OTYPE);
        dto.setOutLineLevel(obj.getString("outLineLevel"));
        dto.setOutLineNumber(obj.getString("outLineNumber"));
        dto.setOwnerOID(obj.getString("ownerOID"));
        dto.setOwnerGroupOid(obj.getString("ownerGroupOid"));
        dto.setRatedHours("0");
        dto.setRiskType("UNAVAILABLE");
        dto.setSecurityLabels("非密");
        dto.setTypeOID("264465053392879616");
        dto.setTypeOTYPE(TableTypeConstrant.TY_TYPE_OTYPE);

        list.add(dto);

        JSONArray children = obj.getJSONArray("children");
        if (children != null && !children.isEmpty()) {
            for (int i = 0; i < children.size(); i++) {
                JSONObject child = children.getJSONObject(i);
                buildTaskDtoRecursive(child, dto.getOid(), list);
            }
        }
    }

    private String formatDateTimeStrWithSeconds(String dateTimeStr) {
        if (dateTimeStr == null) return null;
        return dateTimeStr.replace("T", " ");
    }


    private Map<String, List<String>> buildIbaAttribute(CustomExcelImportActiveStrDTO dto) {
        Map<String, List<String>> map = Maps.newConcurrentMap();
        putIfNotBlank(map, "quantity", cleanBracket(dto.getQuantity()));
        putIfNotBlank(map, "processSection", cleanBracket(dto.getProcessSection()));
        putIfNotBlank(map, "productUnitSystem", cleanBracket(dto.getProductUnitSystem()));
        putIfNotBlank(map, "productName", cleanBracket(dto.getProductName()));
        putIfNotBlank(map, "productModel", cleanBracket(dto.getProductModel()));
        putIfNotBlank(map, "productForm", cleanBracket(dto.getProductForm()));
        return map;
    }

    private String cleanBracket(String str) {
        if (str == null) return null;
        str = str.replaceAll("[\\[\\]]", "").trim();
        str = str.replaceAll("^\"|\"$", "").trim();
        return str;
    }

    private void putIfNotBlank(Map<String, List<String>> map, String key, String value) {
        if (StringUtils.isNotBlank(value)) {
            // 去掉小数点后的 .0
            String newValue = value.matches("\\d+\\.0+") ? value.substring(0, value.indexOf('.')) : value;
            String cleanValue = newValue.replaceAll("^\\[|\\]$", "");
            map.put(key, Lists.newArrayList(cleanValue));

        }
    }









}